package com.easydev.mq;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <Description> mq配置类，用于管理相关配置<br>
 * 
 * @author lx<br>
 * @version 1.0<br>
 * @CreateDate 2016年3月14日 <br>
 */
public class MqConfig {

    private final static Logger LOGGER = LoggerFactory.getLogger(MqConfig.class);

    public final static String CONFIG_FILE = "mq.properties";

    protected static Properties config = new Properties();

    static {
        try {
            config = loadConfigResource();
        } catch (Exception e) {
            LOGGER.error("loading mq config failed:" + e.getMessage());
        }
    }

    /**
     * Description: 加载配置文件<br>
     * 1.优先读取classpath下的cache.properties<br>
     * 2.若没有，则读取该文件夹下的默认配置
     * 
     * @return Properties
     * @throws Exception <br>
     */
    private static Properties loadConfigResource() throws Exception {
        LOGGER.info("Load Config File : [{}].", CONFIG_FILE);
        InputStream configStream = MqConfig.class.getClassLoader().getResourceAsStream(CONFIG_FILE);
        if (null == configStream) {
            configStream = MqConfig.class.getClassLoader().getParent().getResourceAsStream(CONFIG_FILE);
        }
        if (null == configStream) {
            configStream = MqConfig.class.getResourceAsStream(CONFIG_FILE);
        }
        if (null == configStream) {
            throw new FileNotFoundException("Cannot find " + CONFIG_FILE + " !!!");
        }
        Properties props = new Properties();
        try {
            props.load(configStream);
        } finally {
            configStream.close();
        }
        return props;
    }
}
